<?php
include_once 'data.php';
include_once 'functions.php';

if (isset($_GET['file']) && isset($_SESSION['auth'])) {

	database_connect($database_path, 'library');
	
	$user_query = $dbHandle->quote($_SESSION['user_id']);
	$file_query = $dbHandle->quote($_GET['file']);
	
	$result = $dbHandle->query("SELECT rowid FROM shelves WHERE userID=$user_query AND fileID=$file_query LIMIT 1");
	$relation = $result->fetchColumn();
	$result = null;

	if (!$relation) {
		$update = $dbHandle->exec("INSERT OR IGNORE INTO shelves (userID,fileID) VALUES ($user_query,$file_query)");
		if($update) echo 'added';
	} else {
		$update = $dbHandle->exec("DELETE FROM shelves WHERE rowid=$relation");
              if (isset($_GET['selection']) && $_GET['selection'] == 'shelf') {

function save_export_files ($filename, $files, $timestamp) {
    $export_files = array ();
    $export_files['timestamp'] = $timestamp;
    $export_files['files'] = $files;
    $export_files_content = serialize ($export_files);
    file_put_contents($filename, $export_files_content, LOCK_EX);
}

                  $cached_files_file = $temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id().DIRECTORY_SEPARATOR.'exportfiles.txt';

                  if(is_readable($cached_files_file)) {
                      $export_files_content = file_get_contents($cached_files_file);
                      $export_files_array = unserialize ($export_files_content);
                      $export_files_timestamp = $export_files_array['timestamp'];
                      $export_files = $export_files_array['files'];
                  }

			unset($export_files[array_search($_GET['file'], $export_files)]);
			$export_files = array_values($export_files);
                     save_export_files ($cached_files_file, $export_files, time());
		}
		if($update) echo 'removed';
	}

	$dbHandle = null;
}
?>